import fs from "node:fs";
import path from "node:path";
import { Buffer } from "node:buffer";

const mxlog = "/home/wen/code/benz/out/log";

let offset = 0;
let fileName = "";

function findNewestFile() {
  let lastTime = 0;
  fs.readdirSync(mxlog).forEach(file => {
    if (file.startsWith('mxlog')) {
      const fullPath = path.join(mxlog, file);
      const stats = fs.statSync(fullPath);
      if (stats.isFile() && stats.mtimeMs > lastTime) {
        lastTime = stats.mtimeMs;
        fileName = fullPath;
      }
    }
  });
}

function printLog(fd) {
  const stats = fs.statSync(fileName);
  const buffer = Buffer.alloc(stats.size - offset);
  fs.read(fd, buffer, 0, buffer.length, offset, (err, bytes) => {
    const str = buffer.toString();
    console.log(str)
    offset = stats.size;
  });
}

function watchFile() {
  fs.open(fileName, "r", (err, fd) => {
    printLog(fd);
    fs.watch(fileName, () => {
      printLog(fd);
    });
  })
}

findNewestFile();
watchFile();
